package com.ysy.oauthclient.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author ysy
 */
@Configuration
public class MyOauthResourceConfig extends ResourceServerConfigurerAdapter {

    private final static String RESOURCE_ID="client";

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                //资源ID
                //.resourceId(RESOURCE_ID)
                //使用远程服务验证令牌的服务
                //.tokenServices(tokenServices())
                // 本地认证就好，不用请求远程。不然每次都请求浪费
                .tokenStore(tokenStore)
                //无状态模式
                .stateless(true);

    }

    /**
     * 配置access_token远程验证策略。
     */
    public ResourceServerTokenServices tokenServices() {
        RemoteTokenServices services = new RemoteTokenServices();
        services.setClientId("c1");
        services.setClientSecret("secret");
        services.setCheckTokenEndpointUrl("http://localhost:5201/oauthService/oauth/check_token");
        return services;
    }



    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 路径匹配规则。
                .antMatchers("/hello/**")
                // 需要匹配scope  "#oauth2.hasScope('all')"
                .access("#oauth2.hasScope('all')");
       // super.configure(http);
    }
}
